<template>
  <div class="chat-container">
    <div class="chat-header">
      <h1>DeepSeek 聊天助手</h1>
      <div class="function-buttons">
        <button @click="handleSearch">演唱会模糊查询</button>
        <button @click="handleRecommend">推荐演唱会</button>
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <div
          v-for="(msg, index) in messages"
          :key="index"
          :class="['message', msg.role]"
      >
        <div class="avatar">
          {{ msg.role === 'user' ? '我' : 'AI' }}
        </div>
        <div class="content">
          <template v-if="msg.type === 'concertList'">
            <div class="concert-list">
              <h4>{{ msg.title }}</h4>
              <div class="concert-item" v-for="(item, i) in msg.content" :key="i">
                <h5>{{ item.title }}</h5>
                <p>艺人: {{ item.artist }}</p>
                <p>时间: {{ formatDate(item.startdate) }}</p>
                <p>地点: {{ item.venueName || '未知场地' }}</p>
              </div>
            </div>
          </template>
          <template v-else>
            {{ msg.content }}
          </template>
        </div>
      </div>
      <div v-if="loading" class="loading">正在思考中...</div>
    </div>

    <div class="chat-input">
      <textarea
          v-model="inputMessage"
          placeholder="请输入消息... 可以尝试搜索演唱会或请求推荐"
          @keydown.enter.exact="sendMessage"
          @keydown.enter.shift="() => {}"
      ></textarea>
      <button @click="sendMessage" :disabled="!inputMessage.trim() || loading">
        发送
      </button>
    </div>
  </div>
</template>

<script>
import deepSeekApi from '../api/deepSeek_api.js'
import concertApi from '../api/concert_api.js'

export default {
  data() {
    return {
      messages: [],
      inputMessage: '',
      loading: false
    }
  },
  methods: {
    async sendMessage() {
      const message = this.inputMessage.trim()
      if (!message || this.loading) return

      this.messages.push({ role: 'user', content: message })
      this.inputMessage = ''
      this.loading = true

      try {
        if (message.includes('搜索') && message.includes('演唱会')) {
          const keyword = message.replace(/搜索|演唱会/g, '').trim()
          await this.searchConcerts(keyword || message)
        } else if (message.includes('推荐') && message.includes('演唱会')) {
          await this.recommendConcerts()
        } else {
          const response = await deepSeekApi.chat(message)
          const content = response.data?.choices?.[0]?.message?.content || '未获取到有效回复'
          this.messages.push({ role: 'assistant', content })
        }
      } catch (error) {
        this.messages.push({
          role: 'assistant',
          content: `发生错误: ${error.message || '未知错误'}`
        })
        console.error('请求失败:', error)
      } finally {
        this.loading = false
        this.scrollToBottom()
      }
    },

    async handleSearch() {
      const keyword = prompt('请输入搜索关键词（演唱会名称或艺人）:')
      if (keyword) {
        this.messages.push({ role: 'user', content: `搜索演唱会: ${keyword}` })
        this.loading = true
        try {
          await this.searchConcerts(keyword)
        } catch (error) {
          this.messages.push({
            role: 'assistant',
            content: `搜索失败: ${error.message || '未知错误'}`
          })
        } finally {
          this.loading = false
          this.scrollToBottom()
        }
      }
    },

    async handleRecommend() {
      this.messages.push({ role: 'user', content: '请推荐一些演唱会' })
      this.loading = true
      try {
        await this.recommendConcerts()
      } catch (error) {
        this.messages.push({
          role: 'assistant',
          content: `推荐失败: ${error.message || '未知错误'}`
        })
      } finally {
        this.loading = false
        this.scrollToBottom()
      }
    },

    async searchConcerts(keyword) {
      const response = await concertApi.search(keyword);
      if (response && response.length > 0) {
        this.messages.push({
          role: 'assistant',
          type: 'concertList',
          content: response,
          title: `找到包含"${keyword}"的演唱会:`
        });
      } else {
        this.messages.push({
          role: 'assistant',
          content: `没有找到包含"${keyword}"的演唱会`
        });
      }
    },

    async recommendConcerts() {
      const response = await concertApi.recommend();
      if (response && response.length > 0) {
        this.messages.push({
          role: 'assistant',
          type: 'concertList',
          content: response,
          title: '为您推荐的演唱会:'
        });
      } else {
        this.messages.push({
          role: 'assistant',
          content: '暂时没有可推荐的演唱会'
        });
      }
    },

    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },

    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer
        container.scrollTop = container.scrollHeight
      })
    }
  },
  mounted() {
    this.messages.push({
      role: 'assistant',
      content: '你好！我是DeepSeek AI助手，可以帮你查询和推荐演唱会。你可以输入关键词搜索，或点击上方按钮进行操作。'
    })
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.chat-header {
  background-color: #f5f5f5;
  padding: 16px;
  text-align: center;
  border-bottom: 1px solid #e0e0e0;
  position: relative;
}

.function-buttons {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.function-buttons button {
  padding: 6px 12px;
  background-color: #6c757d;
  font-size: 14px;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background-color: #fafafa;
}

.message {
  display: flex;
  margin-bottom: 16px;
  max-width: 80%;
}

.message.user {
  flex-direction: row-reverse;
  margin-left: auto;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  font-size: 14px;
}

.message.user .avatar {
  margin-right: 0;
  margin-left: 8px;
  background-color: #007bff;
  color: white;
}

.content {
  padding: 8px 16px;
  border-radius: 18px;
  background-color: #e9e9eb;
  line-height: 1.5;
}

.message.user .content {
  background-color: #007bff;
  color: white;
}

.concert-list {
  margin-top: 8px;
}

.concert-item {
  padding: 8px;
  margin-bottom: 8px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
}

.message.user .concert-item {
  background-color: rgba(255, 255, 255, 0.2);
}

.loading {
  text-align: center;
  padding: 16px;
  color: #666;
}

.chat-input {
  display: flex;
  padding: 16px;
  border-top: 1px solid #e0e0e0;
}

textarea {
  flex: 1;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  resize: none;
  outline: none;
  font-size: 14px;
  min-height: 48px;
}

button {
  margin-left: 12px;
  padding: 0 24px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  white-space: nowrap;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>